﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;

namespace CIRDiagnoseDevice.Test
{
    class TrainApproachEarlyWarning
    {
        private SendTaxData sendTaxData = new SendTaxData();
        private InitSerialPort inite = new InitSerialPort();
        private SerialPort PocsagCodePort;
        private byte[] RBuffer = new byte[500]; // 缓存串口接收数据
        private  List< byte> RXBuffer = new List<byte>();// 转存接收数据
        private bool haveReceivePocsagCode;
        private DataGridView dgv;
        private int startIndex;
        public event MessageNotice OnMessageNotice;

        public void StartTrainApproachTrial(ref Thread TrainApproachThread)
        {
            TrainApproachThread = new Thread(new ThreadStart(SendTaxData));
            TrainApproachThread.IsBackground = true;
            TrainApproachThread.Start();
        }

        public void ClearSource()
        {
            PocsagCodePort.Close();
            PocsagCodePort.DataReceived -= new SerialDataReceivedEventHandler(PocsagCodePort_DataReceived);
            GC.Collect();
        }

        public void SendTaxData()
        {
            MainFrm.MotherFrm.TrainApproachEarly_Warning = true;
            byte[] data = sendTaxData.SendDigData(0x05, (ushort)125);
            if (PocsagCodePort.IsOpen)
            {
                while (!haveReceivePocsagCode)
                {
                    PocsagCodePort.Write(data, 0, data.Length);
                }
            }
        }

        public TrainApproachEarlyWarning(SerialPort PocsagCodePort, DataGridView dgv, int startIndex)
        {
            this.PocsagCodePort = PocsagCodePort;
            this.dgv = dgv;
            this.startIndex = startIndex;
        }

        public void InitParameter()
        {
            inite.Open(PocsagCodePort);
            PocsagCodePort.DataReceived += new SerialDataReceivedEventHandler(PocsagCodePort_DataReceived);
            PocsagCodePort.ReadTimeout = 20000;
            Array.Clear(RBuffer, 0, RBuffer.Length);
            RXBuffer.Clear();
            haveReceivePocsagCode = false;
        }

        void PocsagCodePort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            while (!MainFrm.MotherFrm.StopTest)
            {
                while (!MainFrm.MotherFrm.Suspend)
                {
                    if (MainFrm.MotherFrm.TrainApproachEarly_Warning)
                    {
                        int num = 0;
                       
                        try
                        {
                            num = PocsagCodePort.Read(RBuffer, 0, RBuffer.Length);
                            byte[] temp = new byte[num];
                            Array.Copy(RBuffer, 0, temp, 0, num);
                            RXBuffer.AddRange(temp);
                            if (RXBuffer.Count > 8 && !haveReceivePocsagCode)
                            {
                                byte[] temp1 = new byte[8];
                                RXBuffer.CopyTo(0, temp1, 0, 8);
                                StringBuilder str = new StringBuilder();
                                for(int i = 0; i < temp1.Length; i++)
                                {
                                    str.Append(temp1[i].ToString("X"));
                                }
                                string pocStr = str.ToString();
                                string[] strArr = pocStr.Split(new Char[] {'C'});
                                RXBuffer.RemoveRange(0, 9);
                                FillGridWithJudgeResult(dgv, startIndex, "合格", true);
                                haveReceivePocsagCode = true;
                                MessageBox.Show("列车接近预警功能试验完成！");
                                if (OnMessageNotice != null)
                                {
                                    OnMessageNotice(this, ThreadRunState.End);
                                }
                                if (!MainFrm.MotherFrm.IsTestTotal)
                                {
                                    MainFrm.MotherFrm.TrainApproachEarly_Warning = false;
                                    MainFrm.MotherFrm.TrainApproachTrialSaved = false;
                                    MainFrm.MotherFrm.ChangeButtonText();
                                    MainFrm.MotherFrm.StopTest = true;
                                    MainFrm.MotherFrm.Suspend = true;
                                    PocsagCodePort.Close();
                                }
                            }
                        }
                        catch (Exception e1)
                        {
                            if (e1.GetType() == typeof(TimeoutException))
                            {
                                if (MainFrm.MotherFrm.TrainApproachEarly_Warning)
                                {
                                    FillGridWithJudgeResult(dgv, startIndex, "不合格", false);
                                    haveReceivePocsagCode = true;
                                    MessageBox.Show("列车接近预警功能试验完成！");
                                    if (OnMessageNotice != null)
                                    {
                                        OnMessageNotice(this, ThreadRunState.End);
                                    }
                                    if (!MainFrm.MotherFrm.IsTestTotal)
                                    {
                                        MainFrm.MotherFrm.TrainApproachEarly_Warning = false;
                                        MainFrm.MotherFrm.TrainApproachTrialSaved = false;
                                        MainFrm.MotherFrm.ChangeButtonText();
                                        MainFrm.MotherFrm.StopTest = true;
                                        MainFrm.MotherFrm.Suspend = true;
                                        PocsagCodePort.Close();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        public ulong BCDToHex(ulong pbcd, uint num)//BCD码转换成HEX码
        {
            int i;
            ulong pdiv, pmul;

            byte[] tmp = new byte[num];
            pdiv = pbcd;
            for (i = 0; i < num; i++)
            {
                tmp[i] = (byte)(pdiv % 0x10);
                pdiv = pdiv / 0x10;
            }
            pmul = 1;
            pdiv = 0;
            for (i = 0; i < num; i++)
            {
                pdiv = pdiv + pmul * tmp[i];
                pmul = pmul * 10;
            }
            return pdiv;
        }

        //将测试判断结果填写到测试表中
        private void FillGridWithJudgeResult(DataGridView gridview, int rowIndex, string result, bool isGreen)
        {
            gridview.Rows[rowIndex].Cells["试验结果"].Value = result;
            if (isGreen)
                gridview.Rows[rowIndex].Cells["试验结果"].Style.ForeColor = Color.Green;
            else
                gridview.Rows[rowIndex].Cells["试验结果"].Style.ForeColor = Color.Red;
            gridview.Invoke(new MethodInvoker(delegate
            {
                gridview.Refresh();
            }));
        }
    }
}
